package view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

import controller.BerichtsheftController;
import data.Lang;
import data.Settings;

public class SettingsDialog {

	private JDialog dialog;
	private JButton buttonSpeichern;
	private JLabel labelTopText, labelReminder, labelReminder2,labelfortlaufendeNummer;
	private JCheckBox checkboxReminder;
	private JTextField textfieldReminderHour, textfieldReminderMinutes,textfieldfortlaufendeNummer;
	private JTextField textfieldDirectory;
	private JButton buttonChooseDir;
	
	private ButtonHandler buttonHandler;
	
	private BerichtsheftController bhc;
	private Settings settings;
	
	private boolean editMode;
	
	public SettingsDialog(BerichtsheftController bhc, Settings settings, boolean editMode){
		this.bhc = bhc;
		this.settings = settings;
		this.editMode = editMode;
		
		buttonHandler = new ButtonHandler();
		dialog = new JDialog();
		dialog.setTitle(editMode?Lang.SETTINGS_TITLE_EDIT:Lang.SETTINGS_TITLE_WELCOME);
		dialog.setSize(515, 235);
		dialog.setResizable(false);
		dialog.setMinimumSize(dialog.getSize());
		dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		dialog.setLocationRelativeTo(null);
		dialog.setModal(true);
		dialog.setLayout(null);
		setupGUI(editMode);
		dialog.setVisible(true);
	}
	
	private void setupGUI(boolean editMode){
		
		labelTopText = new JLabel();
		if(!editMode) {
			labelTopText.setText(Lang.SETTINGS_MSG_WELCOME);
		} else {
			labelTopText.setText(Lang.SETTINGS_MSG_EDIT);
		}
		labelTopText.setVerticalAlignment(JLabel.TOP);
		labelTopText.setBounds(20, 15, 500, 75);
		dialog.add(labelTopText);
		
		labelReminder = new JLabel(Lang.SETTINGS_LABEL_REMTIME);
		labelReminder.setBounds(145, 70, 40, 20);
		labelReminder.setEnabled(false);
		dialog.add(labelReminder);
		
		labelReminder2 = new JLabel(":");
		labelReminder2.setBounds(220, 70, 10, 20);
		labelReminder2.setEnabled(false);
		labelReminder2.setHorizontalAlignment(JLabel.CENTER);
		dialog.add(labelReminder2);
		
		labelfortlaufendeNummer = new JLabel(Lang.SETTINGS_LABEL_STARTWEEK);
		labelfortlaufendeNummer.setBounds(20, 100, 170, 20);
		dialog.add(labelfortlaufendeNummer);
		
		textfieldfortlaufendeNummer = new JTextField();
		textfieldfortlaufendeNummer.setBounds(190, 100, 30, 20);
		textfieldfortlaufendeNummer.setText(""+settings.getFortlaufendeNrStart());
		textfieldfortlaufendeNummer.setEnabled(!editMode);
		((AbstractDocument) textfieldfortlaufendeNummer.getDocument()).setDocumentFilter(new OnlyNumbersFilter());
		dialog.add(textfieldfortlaufendeNummer);
		
		textfieldReminderHour = new JTextField();
		textfieldReminderHour.setBounds(190, 70, 30, 20);
		textfieldReminderHour.setEnabled(false);
		textfieldReminderHour.setText("" + settings.getReminderTimeHour());
		((AbstractDocument) textfieldReminderHour.getDocument()).setDocumentFilter(new TimeFilter());
		dialog.add(textfieldReminderHour);
		
		textfieldReminderMinutes = new JTextField();
		textfieldReminderMinutes.setBounds(230, 70, 30, 20);
		textfieldReminderMinutes.setEnabled(false);
		textfieldReminderMinutes.setText((("" + settings.getReminderTimeMinutes()).length() < 2?"0":"") + "" + settings.getReminderTimeMinutes());
		((AbstractDocument) textfieldReminderMinutes.getDocument()).setDocumentFilter(new TimeFilter());
		dialog.add(textfieldReminderMinutes);
		
		checkboxReminder = new JCheckBox(Lang.SETTINGS_LABEL_DAILYREM);
		checkboxReminder.setBounds(15, 70, 130, 20);
		checkboxReminder.addItemListener(new CheckHandler());
		checkboxReminder.setSelected(settings.getShowDailyReminder());
		dialog.add(checkboxReminder);
		
		
		textfieldDirectory = new JTextField();
		textfieldDirectory.setBounds(20, 130, 300, 24);
		textfieldDirectory.setText(settings.getWeekDirectoryForSettings());
		dialog.add(textfieldDirectory);
		
		
		buttonChooseDir = new JButton(Lang.SETTINGS_BTN_CHOOSEDIR);
		buttonChooseDir.setBounds(320, 130, 120, 24);
		buttonChooseDir.addActionListener(buttonHandler);
		
		dialog.add(buttonChooseDir);
		
		buttonSpeichern = new JButton(editMode?Lang.SETTINGS_BTN_EDIT:Lang.SETTINGS_BTN_WELCOME);
		buttonSpeichern.setBounds(270, 170, 225, 24);
		buttonSpeichern.addActionListener(buttonHandler);
		dialog.add(buttonSpeichern);
		
	}
	
	class CheckHandler implements ItemListener {
		@Override
		public void itemStateChanged(ItemEvent e) {
			boolean newState = e.getStateChange() == ItemEvent.SELECTED?true:false;
			labelReminder.setEnabled(newState);
			labelReminder2.setEnabled(newState);
			textfieldReminderHour.setEnabled(newState);
			textfieldReminderMinutes.setEnabled(newState);
		}
	}
	
	class ButtonHandler implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent event) {
			JComponent source = (JComponent) event.getSource();
			
			if (source == buttonSpeichern) {
				//settings in settings obj und file schreiben, ggf registry, dialog schließen
				settings.setShowDailyReminder(checkboxReminder.isSelected());
				settings.setReminderTimeHour(textfieldReminderHour.getText());
				settings.setReminderTimeMinutes(textfieldReminderMinutes.getText());
				settings.setFortlaufendeNummer(textfieldfortlaufendeNummer.getText());
				if(!settings.getWeekDirectoryForSettings().equals(textfieldDirectory.getText()) && editMode) {
					bhc.getData().loadWochenFromFiles();
					File oldDir = settings.getWeekDirectoryFile();
					settings.setWeekDirectory(textfieldDirectory.getText());
					bhc.getData().saveWochenToFiles(true);
					File[] list = oldDir.listFiles();
					for(File f : list) f.delete();
					oldDir.delete();
				} else {
					
				}
				settings.setWeekDirectory(textfieldDirectory.getText());
				bhc.writeSettingsFile();
				bhc.setAutostartInRegistry(settings.getShowDailyReminder());
				dialog.dispose();
			}
			if(source == buttonChooseDir) {
				JFileChooser jfc = new JFileChooser();
				jfc.setCurrentDirectory(new File(textfieldDirectory.getText()));
				jfc.setDialogTitle(Lang.SETTINGS_FOLDERCHOOSER_TITLE);
				jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				jfc.setAcceptAllFileFilterUsed(false);
				if(jfc.showOpenDialog(dialog) == JFileChooser.APPROVE_OPTION) {
					textfieldDirectory.setText(jfc.getSelectedFile().getPath());
				}
				
			}
		}
	}
	
	class TimeFilter extends DocumentFilter { // erlaubt nciht mehr als zwei buchstaben und nur zahlen
		@Override
		public void replace(FilterBypass fb, int i, int i1, String string, AttributeSet as) throws BadLocationException {
			int length = fb.getDocument().getText(0, fb.getDocument().getLength()).length();// + string.length();
			for (int n = string.length(); n > 0; n--) {// an inserted string may be more than a single character i.e a copy and paste of 'aaa123d', also we iterate from the back as super.XX implementation will put last insterted string first and so on thus 'aa123d' would be 'daa', but because we iterate from the back its 'aad' like we want
				char c = string.charAt(n - 1);// get a single character of the string
				if (!String.valueOf(c).matches("\\D") && length < 2) {// Solang es kein Semikolon ist, ist alles gut
					super.replace(fb, i, i1, String.valueOf(c), as);// allow update to take place for the given character
					length++;
				} else {
					// do nothing
				}
			}
		}
	}
	
	class OnlyNumbersFilter extends DocumentFilter { // erlaubt nciht mehr als zwei buchstaben und nur zahlen
		@Override
		public void replace(FilterBypass fb, int i, int i1, String string, AttributeSet as) throws BadLocationException {
			for (int n = string.length(); n > 0; n--) {// an inserted string may be more than a single character i.e a copy and paste of 'aaa123d', also we iterate from the back as super.XX implementation will put last insterted string first and so on thus 'aa123d' would be 'daa', but because we iterate from the back its 'aad' like we want
				char c = string.charAt(n - 1);// get a single character of the string
				if (Character.isDigit(c)) {// Solang es eine Zahl  ist, ist alles gut
					super.replace(fb, i, i1, String.valueOf(c), as);// allow update to take place for the given character
				} else {
					// do nothing
				}
			}
		}
	}

}
